package com.wending.main_page;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.wending.R;
import com.wending.application.MyApplication;
import com.wending.base_method.NetworkDetector;
import com.wending.bean.User;
import com.wending.config.Constant;
import com.wending.onekeyshare.OnekeyShare;
import com.wending.onekeyshare.OnekeyShareTheme;
import com.wending.view.ProgressWebView;
import com.wending.webuploadimg.ImageUtil;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by 张英杰 on 2017/1/23.
 */

public class MyWebViewFragment extends Fragment {
//    cyh cyh
//admin  admin
//    niutuvip  19941001

    private ProgressWebView mWebView;
    public boolean dispose = false;//是否处理 回退事件
    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private Intent mSourceIntent;
    private ValueCallback<Uri> mUploadMsg = null;
    private ValueCallback<Uri[]> mUploadMsgSSS = null;

    protected BackHandlerInterface backHandlerInterface;
    private String webTitle;
    private String weburl;
    private CookieManager cookieManager;
    private AlertDialog.Builder builder;
    private ImageView iv_share;
    private Context context;

//
//        final String imageMimeType = "image/*";
//          final String videoMimeType = "video/*";
//           final String audioMimeType = "audio/*";
//            final String mediaSourceKey = "capture";
//            final String mediaSourceValueCamera = "camera";
//             final String mediaSourceValueFileSystem = "filesystem";
//          final String mediaSourceValueCamcorder = "camcorder";
//          final String mediaSourceValueMicrophone = "microphone";

//        115        // Parse the accept type.
//        116        String params[] = acceptType.split(";");
//        117        String mimeType = params[0];
//        118
//        119        for (String p : params) {
//            120            String[] keyValue = p.split("=");
//            121            if (keyValue.length == 2) {
//                122                // Process key=value parameters.
//                123                if (mediaSourceKey.equals(keyValue[0])) {
//                    124                    mediaSource = keyValue[1];
//                    125                }
//                126            }
//            127        }
//        128
//        129        //Ensure it is not still set from a previous upload.
//        130        mCameraFilePath = null;
//        131
//        132        if (mimeType.equals(imageMimeType)) {
//            133            if (mediaSource.equals(mediaSourceValueCamera)) {
//                134                // Specified 'image/*' and requested the camera, so go ahead and launch the
//                135                // camera directly.
//                136                startActivity(createCameraIntent());
//                137                return;
//                138            } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
//                139                // Specified 'image/*' and requested the filesystem, so go ahead and launch an
//                140                // OPENABLE intent.
//                141                startActivity(createOpenableIntent(imageMimeType));
//                142                return;
//                143            } else {
//                144                // Specified just 'image/*', so launch an intent for both the Camera and image/*
//                145                // OPENABLE.
//                146                Intent chooser = createChooserIntent(createCameraIntent());
//                147                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
//                148                startActivity(chooser);
//                149                return;
//                150            }
//            151        } else if (mimeType.equals(videoMimeType)) {
//            152            if (mediaSource.equals(mediaSourceValueCamcorder)) {
//                153                // Specified 'video/*' and requested the camcorder, so go ahead and launch the
//                154                // camcorder directly.
//                155                startActivity(createCamcorderIntent());
//                156                return;
//                157            } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
//                158                // Specified 'video/*' and requested the filesystem, so go ahead and launch an
//                159                // an OPENABLE intent.
//                160                startActivity(createOpenableIntent(videoMimeType));
//                161                return;
//                162            } else {
//                163                // Specified just 'video/*', so go ahead and launch an intent for both camcorder and
//                164                // video/* OPENABLE.
//                165                Intent chooser = createChooserIntent(createCamcorderIntent());
//                166                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
//                167                startActivity(chooser);
//                168                return;
//                169            }
//            170        } else if (mimeType.equals(audioMimeType)) {
//            171            if (mediaSource.equals(mediaSourceValueMicrophone)) {
//                172                // Specified 'audio/*' and requested microphone, so go ahead and launch the sound
//                173                // recorder.
//                174                startActivity(createSoundRecorderIntent());
//                175                return;
//                176            } else if (mediaSource.equals(mediaSourceValueFileSystem)) {
//                177                // Specified 'audio/*' and requested filesystem, so go ahead and launch an
//                178                // OPENABLE intent.
//                179                startActivity(createOpenableIntent(audioMimeType));
//                180                return;
//                181            } else {
//                182                // Specified just 'audio/*', so go ahead and launch an intent for both the sound
//                183                // recorder and audio/* OPENABLE.
//                184                Intent chooser = createChooserIntent(createSoundRecorderIntent());
//                185                chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
//                186                startActivity(chooser);
//                187                return;
//                188            }
//            189        }
//        190
//        191        // No special handling based on the accept type was necessary, so trigger the default
//        192        // file upload chooser.
//        193        startActivity(createDefaultOpenableIntent());

    //dialog显示
    public void showOptions() {
        checkLocalPermission();
//        android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(context);
//        alertDialog.setOnCancelListener(new ReOnCancelListener());
//        alertDialog.setTitle("操作");
//        alertDialog.setItems(
//                R.array.options,
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        mSourceIntent = ImageUtil.choosePicture();
//                        startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
//                    }
//                }
//        );
//        alertDialog.show();
    }

    public interface BackHandlerInterface {
        void setSelectedFragment(MyWebViewFragment backHandledFragment);

        void webViewTunFragment(int position);//1登录
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
        weburl = getArguments().getString("data");
        if (TextUtils.isEmpty(Constant.localCookie) && (DataSupport.findFirst(User.class) != null)) {
            Login(context);
        }
    }

    private int loginCount = 0;
    StringRequest loginRequest;

    private void Login(final Context context) {
        List<User> all = DataSupport.findAll(User.class);
        if (all != null && all.size() > 0 && all.get(0) != null) {
            User user = all.get(0);
            String url = Constant.Login + "?password=" + user.getPassword() + "&username=" + user.getUsername();
            loginRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    loginCount++;
                    Log.i("LLLoginWebFragment====", " loginCount==" + loginCount + "--volleyError--" + volleyError.toString());
                    if (NetworkDetector.detect(context) && loginCount < 50) {
                        MyApplication.requestQueue.add(loginRequest);
                        MyApplication.requestQueue.start();
                    }
                }
            }) {
                //重写parseNetworkResponse方法，返回的数据中 Set-Cookie:***************;
                //其中**************为session id
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    Response<String> superResponse = super
                            .parseNetworkResponse(response);
                    Map<String, String> responseHeaders = response.headers;
                    String rawCookies = responseHeaders.get("Set-Cookie");
                    //Constant是一个自建的类，存储常用的全局变量
                    Constant.localCookie = rawCookies.substring(0, rawCookies.indexOf(";"));
                    Log.d("新的sessionid", "LLLLogin======" + Constant.localCookie);
                    if (mWebView != null) {
                        String currentUrl = mWebView.getUrl();
                        String cookie = cookieManager.getCookie(currentUrl);
                        if ((TextUtils.isEmpty(cookie)) || ((!TextUtils.isEmpty(Constant.localCookie) && (!cookie.equals(Constant.localCookie))))) {
                            cookieManager.removeAllCookie();
                            cookieManager.setCookie(currentUrl, Constant.localCookie);
                            CookieSyncManager.getInstance().sync();
                            mWebView.reload();
                        }
                    }
                    return superResponse;
                }
            };
            MyApplication.requestQueue.add(loginRequest);
            MyApplication.requestQueue.start();
        }
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            backHandlerInterface = (BackHandlerInterface) getActivity();
        } catch (Exception e) {
            throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
        }
    }

    public void onStart() {
        super.onStart();
        backHandlerInterface.setSelectedFragment(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        fixDirPath();
    }

    private void fixDirPath() {
        String path = ImageUtil.getDirPath();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.webview_fragment, container, false);
        CookieSyncManager.createInstance(context);
        cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        builder = new AlertDialog.Builder(context)
                .setTitle("请先登录")
                .setMessage("是否到登录界面登录")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        backHandlerInterface.webViewTunFragment(1);
                    }
                })
                .setNegativeButton("否", null);
        init(view);
        setLoginView(view);
        return view;
    }

    private boolean isVisibleTo_User = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisibleTo_User = isVisibleToUser;
        if (isVisibleToUser && weburl != null && weburl.equals(Constant.liaoTian) && mWebView != null) {
            String currentUrl = mWebView.getUrl();
            if (!TextUtils.isEmpty(Constant.localCookie)) {
                cookieManager.removeAllCookie();
                cookieManager.setCookie(currentUrl, Constant.localCookie);
                CookieSyncManager.getInstance().sync();
                mWebView.reload();
                backHandlerInterface.webViewTunFragment(-2);
            } else {
                tunLoginDialog();
            }
        }
        isTurnLoginOrRefreshCookie();
    }

    //跳转登录的方法
    private void tunLoginDialog() {
        mWebView.setVisibility(View.GONE);
        builder.show();
    }

    //设置登录按钮
    private void setLoginView(View view) {
        int registe = getArguments().getInt("registe");
        if (registe == 1) {
            view.findViewById(R.id.rl).setVisibility(View.VISIBLE);
            view.findViewById(R.id.tvLogin).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    backHandlerInterface.webViewTunFragment(1);
                }
            });
        } else {
            view.findViewById(R.id.rl).setVisibility(View.GONE);
        }
    }

    private boolean isOnPageFinish = false;

    private void init(View view) {
        iv_share = (ImageView) view.findViewById(R.id.iv_share);
        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        mWebView = (ProgressWebView) view.findViewById(R.id.wv);
        WebSettings settings = mWebView.getSettings();
//        settings.setDefaultTextEncodingName("utf-8");//其实这句话的作用就相当于网页的元信息，相当与一个meta。
        settings.setDefaultTextEncodingName("GBK");//其实这句话的作用就相当于网页的元信息，相当与一个meta。
//        设置网页布局类型：
//        *  1、LayoutAlgorithm.NARROW_COLUMNS ： 适应内容大小
//        *  2、LayoutAlgorithm.SINGLE_COLUMN: 适应屏幕，内容将自动缩放  有些网页混乱！！！飞起
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);//设置缓存
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

        String cloadUrl = weburl + "?data=" + System.currentTimeMillis() / 1000;

        if (!TextUtils.isEmpty(Constant.localCookie)) {
            cookieManager.removeAllCookie();
            cookieManager.setCookie(cloadUrl, Constant.localCookie);
            CookieSyncManager.getInstance().sync();
            String test = cookieManager.getCookie(cloadUrl);
            Log.i("webfragment===", "通过Url得到的cookie===" + test);
        }
        Log.i("webFragment ", "===当前网址webUrl===" + cloadUrl);
        mWebView.loadUrl(cloadUrl);
//                //加载html
//               webView.loadData(weburl,"text/html","utf-8");//在有些手机上会出现乱码，将方法变成
//                webView.loadDataWithBaseURL(null,weburl,"text/html","utf-8",null);//就可以解决这个
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                isOnPageFinish = false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                isOnPageFinish = true;
                if (isVisibleTo_User && (!TextUtils.isEmpty(webTitle)) && (weburl.equals(Constant.zhuYe) || weburl.equals(Constant.sheQu) && iv_share != null)
//                && webTitle.equals("wenDingGuWanFX"))
                        && webTitle.contains("&wenDingGuWanFX")) {
                    if (iv_share != null) {
                        iv_share.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                Log.i("前进Url===", url);
                if (!TextUtils.isEmpty(Constant.localCookie)) {
                    cookieManager.removeAllCookie();
                    cookieManager.setCookie(url, Constant.localCookie);
                    CookieSyncManager.getInstance().sync();
                    view.loadUrl(url);
                    String test = cookieManager.getCookie(url);
                    Log.i("前进Url===", "通过Url得到的cookie===" + test);
                } else {
                    String test = cookieManager.getCookie(url);
                    Log.i("前进Urlllllll===", "通过Url得到的cookie===" + test);

                    view.loadUrl(url);
                }
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle = title;
                isTurnLoginOrRefreshCookie();
            }

            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                mUploadMsg = uploadFile;
                showOptions();
            }

            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                mUploadMsgSSS = filePathCallback;
                showOptions();
                return true;
            }
        });

        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                Log.i("web返回键DDDDDD===", "KEYCODE_BACK==" + KeyEvent.KEYCODE_BACK
                        + "      webView.canGoBack()==" + mWebView.canGoBack()
                        + "      webView.canGoForward()==" + mWebView.canGoForward()
                );
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_FORWARD && mWebView.canGoForward()) {
                        if (!TextUtils.isEmpty(Constant.localCookie)) {
                            cookieManager.removeAllCookie();
                            String currentUrl = mWebView.getUrl();
                            cookieManager.setCookie(currentUrl, Constant.localCookie);
                            CookieSyncManager.getInstance().sync();
                            String test = cookieManager.getCookie(currentUrl);
                            Log.i("GGGGGGoFFFF===", "通过Url得到的cookie===" + test);
                        }
                        mWebView.reload();
                        mWebView.goForward();   //后退
                        dispose = true;
                        return true;    //已处理
                    } else if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {  //表示按返回键
                        if (!TextUtils.isEmpty(Constant.localCookie)) {
                            cookieManager.removeAllCookie();
                            String currentUrl = mWebView.getUrl();
                            cookieManager.setCookie(currentUrl, Constant.localCookie);
                            CookieSyncManager.getInstance().sync();
                            String test = cookieManager.getCookie(currentUrl);
                            Log.i("GGGGGGoback===", "通过Url得到的cookie===" + test);
                        }
                        mWebView.reload();
                        mWebView.goBack();   //后退
                        dispose = true;
                        return true;    //已处理
                    }
                    dispose = false;
                    return false;
                }
                dispose = false;
                return false;
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
            }
            if (mUploadMsgSSS != null) {
                mUploadMsgSSS.onReceiveValue(null);
            }
        } else {
            switch (requestCode) {
                case REQUEST_CODE_IMAGE_CAPTURE:
                case REQUEST_CODE_PICK_IMAGE: {
                    try {
                        if ((mUploadMsg == null) && (mUploadMsgSSS == null)) {
                            return;
                        } else {
                            String sourcePath = ImageUtil.retrievePath(context, mSourceIntent, data);
                            if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                                Log.w("furl=====", "空---img--sourcePath empty or not exists.");
                                break;
                            }
                            Uri uri = Uri.fromFile(new File(sourcePath));
                            if (mUploadMsg != null) {
                                mUploadMsg.onReceiveValue(uri);
                            }
                            if (mUploadMsgSSS != null) {
                                mUploadMsgSSS.onReceiveValue(new Uri[]{uri});
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }
    }

    //刷新cookie或者跳转登录
    private void isTurnLoginOrRefreshCookie() {
        Log.d("title===", "" + webTitle);
        if (isVisibleTo_User && (!TextUtils.isEmpty(webTitle)) && isOnPageFinish && (weburl.equals(Constant.zhuYe) || weburl.equals(Constant.sheQu) && iv_share != null)
//                && webTitle.equals("wenDingGuWanFX"))
                && webTitle.contains("&wenDingGuWanFX")) {
            iv_share.setVisibility(View.VISIBLE);
        } else {
            if (iv_share != null) {
                iv_share.setVisibility(View.GONE);
            }
        }

        if (isVisibleTo_User && mWebView != null && (!TextUtils.isEmpty(webTitle))) {
            String currentUrl = mWebView.getUrl();
            String cookie = cookieManager.getCookie(currentUrl);
            Log.i("===fragment状态。。。", "currentUrl===" + currentUrl);
            if (TextUtils.isEmpty(cookie)) {
                if (!TextUtils.isEmpty(Constant.localCookie)) {
                    cookieManager.removeAllCookie();
                    cookieManager.setCookie(currentUrl, Constant.localCookie);
                    CookieSyncManager.getInstance().sync();
                    mWebView.reload();
                } else if (webTitle.equals("问鼎登录")) {
                    tunLoginDialog();
                }
            } else {
                if ((!TextUtils.isEmpty(Constant.localCookie)) && (!cookie.equals(Constant.localCookie))) {
                    Log.i("======", cookie + "   ----  " + Constant.localCookie + "      ------------");
                    if (currentUrl != null
//                        && (currentUrl.equals(Constant.zhuYe) || currentUrl.equals(Constant.liaoTian) || currentUrl.equals(Constant.dongTai) || currentUrl.equals(Constant.sheQu) || weburl.equals(Constant.woDe))
                            && (TextUtils.isEmpty(cookie) || (!cookie.equals(Constant.localCookie)))) {
                        cookieManager.removeAllCookie();
                        cookieManager.setCookie(currentUrl, Constant.localCookie);
                        CookieSyncManager.getInstance().sync();
                        mWebView.reload();
                    }
                } else if (webTitle.equals("问鼎登录") && (!weburl.equals(Constant.woDe))) {
                    tunLoginDialog();
                } else if (webTitle.equals("问鼎登录") && (weburl.equals(Constant.woDe))) {
                    backHandlerInterface.webViewTunFragment(-1);
                }
            }
        }
    }

    private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
                mUploadMsg = null;
            }
        }
    }

    private void showShare() {
        String shareTitle = "问鼎分享 ";
        if ((webTitle != null) && (webTitle.contains("&wenDingGuWanFX"))) {
            shareTitle = webTitle.substring(0, webTitle.indexOf("&"));
        }
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle(shareTitle);
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
        oks.setTitleUrl(mWebView.getUrl());
        // text是分享文本，所有平台都需要这个字段
        oks.setText(shareTitle + " " + mWebView.getUrl());//"我是分享文本"
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
//        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImagePath(getImgPath());
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(mWebView.getUrl());
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(mWebView.getUrl());

// 启动分享GUI
        oks.show(context);
    }

    //得到本地分享图片地址
    private String getImgPath() {
        String folder = new String(Environment.getExternalStorageDirectory() + File.separator + "WenDing");
        String fileName = new String("logo.png");
        String imageAddress = folder + File.separator + fileName;
        File file = new File(folder);
        if (!file.exists()) {
            file.mkdirs();
        }
        File f = new File(file + File.separator + fileName);
        if ((f.exists()) && (f.length() > 0)) {
            return imageAddress;
        } else {
            FileOutputStream fos = null;
            try {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                fos = new FileOutputStream(imageAddress);
                if (null != fos) {
                    //数值大小 对照片大小没有影响
                    bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);
                    fos.flush();
                    fos.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imageAddress;
    }

    private static final int MY_PERMISSIONS_REQUEST_WRITE = 22;

    private void checkLocalPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission((Activity) context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions((Activity) context,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_WRITE);
            } else {
                mSourceIntent = ImageUtil.choosePicture();
                startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
            }
        } else {
            mSourceIntent = ImageUtil.choosePicture();
            startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE) {
            if ((grantResults != null) && (grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                mSourceIntent = ImageUtil.choosePicture();
                startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
            } else {
                Toast.makeText(context, "读写权限没有开启无法正常操作", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
